var xhr;
var xhr2;
var xhr3;
var xhr4;
var xhr5;
var preNode;
/*****************************************************************************/
/* search */
function searchProducts(choice) {

    //create xhr
    if (window.ActiveXObject)
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
        xhr = new XMLHttpRequest;

    var searchKey = document.getElementById("searchKey").value;
	var searchOption = document.getElementById("searchOption").value;
    if (choice==0) endNode = 0;
    xhr.onreadystatechange = function() {handleSearchResults(choice);}
    xhr.open("GET", "InventoryServlet?prod_id="+searchKey+"&searchOption="+searchOption, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlendoded");
    xhr.send(null);
}
/*---------------------------------------------------------------------------*/
function handleSearchResults(choice) {

    if (xhr.readyState != 4) return;
    if (xhr.status != 200) {
        alert(xhr.status); // for troubleshooting
        return;
    }
  // alert("get");
    //alert(window.event.srcElement.id);
    /* get the response */
   
    var xhresponse = xhr.responseXML;
    var nodProducts = xhresponse.getElementsByTagName("Product");
    var nodProduct;

    /* get references first*/
    var thd = document.getElementById("thdResults");
    var tbd = document.getElementById("tbdResults");
    var btnDelete = document.getElementById("btnDelete");
    
    
    /* clear revious table*/
    removeChildren(thd);
    removeChildren(tbd);
    if (btnDelete != null)
        document.getElementById("fsetSearch").removeChild(btnDelete);
    

    /* build table header */
    if (nodProducts.length > 0)
        insertHeaderRow(document.getElementById("thdResults"));
       else alert("Sorry, no such poduct found . . ." );
    
    /* build table body */   j=0;
    var currNode;
    if (choice==0) currNode = endNode; else
        if (choice==1) currNode = preNode;
           else currNode = endNode-5;
    for (i=currNode; (i < nodProducts.length) && (j<5); i++,j++) {
        
        nodProduct = nodProducts[i];
		
        strID = nodProduct.getElementsByTagName("ProductID")[0].firstChild.nodeValue;
        strName = nodProduct.getElementsByTagName("ProductName")[0].firstChild.nodeValue;
        strCart = nodProduct.getElementsByTagName("Cart")[0].firstChild.nodeValue;
        strPrice = nodProduct.getElementsByTagName("Price")[0].firstChild.nodeValue;
        strUnits = nodProduct.getElementsByTagName("Units")[0].firstChild.nodeValue;

        insertRow(tbd, strID, strName, strCart, strPrice, strUnits);
    }
     
        endNode=i;
        preNode=i-j-5;
    

    /* build next page button */
    if (i < nodProducts.length ){
       document.getElementById("btnNext").style.display = "inline";
    }  else document.getElementById("btnNext").style.display = "none";
    /* build previouse page button */
    if (i > 5 ){
        document.getElementById("btnPre").style.display = "inline";
    }  else document.getElementById("btnPre").style.display = "none";
    /* build delete button */

    if (nodProducts.length > 0) {

        btnDelete = document.createElement("input");
        btnDelete.setAttribute("id", "btnDelete");
        btnDelete.setAttribute("value", "Delete");
        btnDelete.setAttribute("type", "button");
        btnDelete.setAttribute("class", "ipInline");
        btnDelete.onclick = function() {
        if(window.confirm("Are you sure you want to delete selected product?")) deleteProduct();}
        document.getElementById("fsetSearch").appendChild(btnDelete);
    }
}
/*****************************************************************************/
/* delete employee */
function deleteProduct(){

    /* create xhr */
    if (window.ActiveXObject)
        xhr2 = new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
        xhr2 = new XMLHttpRequest;

    /* put all ids in colon-delimited string */
    var strDeletes = "";

    /* get all checkboxes */
    var chkDeletes = document.getElementsByTagName("input");
    for (i = 0; i < chkDeletes.length; i++) {

        if (chkDeletes.item(i).getAttribute("type") != "checkbox") continue;

        if (chkDeletes[i].checked == false) continue;

        strDeletes += chkDeletes[i].getAttribute("id") + "-";
    }
    /* nothing to delete? */
    if (strDeletes == "") {alert("you did not select any product . ."); return;};
	
   
    /* prepare xhr */
    xhr2.onreadystatechange = handleDeleteResults;
    xhr2.open("GET", "InventoryServlet?prod_id=" + strDeletes + "&searchOption=3", true);
    xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlendoded");
    xhr2.send(null);
}
/*---------------------------------------------------------------------------*/
function handleDeleteResults() {
    var tbd = document.getElementById("tbdResults");
    if (xhr2.readyState != 4) return;
    if (xhr2.status != 200) {
        alert(xhr2.status); // for troubleshooting
        return;
    }
    
    var xhresponse = xhr2.responseXML;
    //var strResults = xhresponse.getElementsByTagName("ID");
    //var tbd = document.getElementById("tbdResults");
    var strResult;
    var myResult="";
	strResult = xhresponse.getElementsByTagName("myDeleteError");
       for (i=0;i<strResult.length;i++) myResult+=strResult[i].firstChild.nodeValue+"\n";
       
    alert (myResult);
    searchProducts(2);
    //var iDeleted = xhresponse.getElementsByTagName("deleteId");
    //for (i = 0; i < iDeleted.length; i++)  deleteRow(tbd, "tr" + iDeleted[i].firstChild.nodeValue);

    
}
/*****************************************************************************/
/*helpers*/
function insertHeaderRow(thd) {

    var tr = document.createElement("tr");

    insertCell(tr, "");     // delete checkbox
    insertCell(tr, "");     // edit button
    insertCell(tr, "ID");
    insertCell(tr, "Product Name");
    insertCell(tr, "Category");
    insertCell(tr, "Price");
	insertCell(tr, "Units avaiable");

    thd.appendChild(tr);
}
/*---------------------------------------------------------------------------*/
function insertRow(tbd, id, name, cart, price, units) {

    /* create new row */
    var tr = document.createElement("tr");
    tr.setAttribute("id", "tr" + id); // for identification later

    /* insert cells to new row */
    insertCheckBox(tr, "chkDelete" + id);
    insertEditButton(tr, "btnEdit" + id);

    insertCell(tr, id);
    insertCell(tr, name);
    insertCell(tr, cart);
    insertCell(tr, price);
	insertCell(tr, units);

    /* add row to table body */
    tbd.appendChild(tr);
}
/*---------------------------------------------------------------------------*/
function deleteRow(tbd, id) {

    var trDelete = document.getElementById(id);
    if (trDelete != null) tbd.removeChild(trDelete);
}
/*---------------------------------------------------------------------------*/
function insertCell(tr, value) {

    var td = document.createElement("td");
    var txtn = document.createTextNode(value);

    td.appendChild(txtn);
    tr.appendChild(td);
}
/*---------------------------------------------------------------------------*/
function insertCheckBox(tr, id) {

    var td = document.createElement("td");
    var chk = document.createElement("input");
    chk.setAttribute("type", "checkbox");
    chk.setAttribute("id", id);
    td.appendChild(chk);
    tr.appendChild(td);
}
/*---------------------------------------------------------------------------*/
function insertEditButton(tr, id) {

    var td = document.createElement("td");
    var btn = document.createElement("input");
    btn.setAttribute("id", id);
    btn.setAttribute("type", "button");
    btn.setAttribute("value", "Edit");
    btn.onclick = function() {displayProduct(id);}

    td.appendChild(btn);
    tr.appendChild(td);
}
/*---------------------------------------------------------------------------*/
function displayProduct(id) {
   
   if (window.ActiveXObject)
        xhr3 = new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
        xhr3 = new XMLHttpRequest;

    xhr3.onreadystatechange = handleDisplayResponse;
    xhr3.open("GET", "InventoryServlet?prod_id="+id+"&searchOption=4", true);
    xhr3.setRequestHeader("Content-Type", "application/x-www-form-urlendoded");
    xhr3.send(null);
}
/*---------------------------------------------------------------------------*/
function resetProduct()
{var resetId = "1234567"+document.getElementById('strProductId').value;
    displayProduct(resetId);

}
function handleDisplayResponse()
{if (xhr3.readyState != 4) return;
    if (xhr3.status != 200) {
        alert(xhr3.status); // for troubleshooting
        return;
    }

    var xhresponse = xhr3.responseXML;
    var nodProducts = xhresponse.getElementsByTagName("Product")[0];
    var temp = nodProducts.getElementsByTagName("ProductID")[0].firstChild.nodeValue;
    document.getElementById("strProductId").value = temp;
    temp = nodProducts.getElementsByTagName("ProductName")[0].firstChild.nodeValue;
    
    document.getElementById("strProductName").value = temp;
    temp = nodProducts.getElementsByTagName("Cart")[0].firstChild.nodeValue;
    document.getElementById("strProductC").value = temp;
    temp = nodProducts.getElementsByTagName("Description")[0].firstChild.nodeValue;
    document.getElementById("strProductD").value = temp;
    temp = nodProducts.getElementsByTagName("Price")[0].firstChild.nodeValue;
    document.getElementById("strProductP").value = temp;
    temp = nodProducts.getElementsByTagName("Units")[0].firstChild.nodeValue;
    document.getElementById("strProductU").value = temp;
    temp = nodProducts.getElementsByTagName("Material")[0].firstChild.nodeValue;
    document.getElementById("strProductM").value = temp;

    editPage();


}
function enable(inputId)
{document.getElementById(inputId).disabled=false;
}
/*---------------------------------------------------------------------------*/
function disable(inputId)
{document.getElementById(inputId).disabled=true;

}
/*---------------------------------------------------------------------------*/
function showup(buttonId)
{
 document.getElementById(buttonId).style.display='inline';
}
/*---------------------------------------------------------------------------*/
function hide(buttonId)
{
 document.getElementById(buttonId).style.display='none';
}
/*---------------------------------------------------------------------------*/
function editPage()
{document.getElementById("addORedit").innerHTML="Edit Product";
      disable('strProductId');
      disable('strProductName');
      disable("strProductC");
      disable("strProductM");
      disable("strProductD");
      disable("strProductP");
      disable("strProductU");
      showup("enN");
      showup("enC");
      showup("enM");
      showup("enD");
      showup("enP");
      showup("enU");
      hide("add");
      showup("save");
      showup("reset");
      showup("addField");
}
/*---------------------------------------------------------------------------*/
function addPage()
{document.getElementById("addORedit").innerHTML="Add Product";
      enable('strProductId');
      enable('strProductName');
      enable("strProductC");
      enable("strProductM");
      enable("strProductD");
      enable("strProductP");
      enable("strProductU");
      hide("enN");
      hide("enC");
      hide("enM");
     hide("enD");
      hide("enP");
      hide("enU");
      showup("add");
      hide("save");
      hide("reset");
      hide("addField");
}
/*---------------------------------------------------------------------------*/
function updateProduct()
{if (window.ActiveXObject)
        xhr4 = new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
        xhr4 = new XMLHttpRequest;


    var prod_id=document.getElementById("strProductId").value;
    var prod_name=document.getElementById("strProductName").value;
    var prod_cart=document.getElementById("strProductC").value;
    var prod_m=document.getElementById("strProductM").value;
    var prod_d=document.getElementById("strProductD").value;
    var prod_p=document.getElementById("strProductP").value;
    var prod_u=document.getElementById("strProductU").value;
    
    xhr4.onreadystatechange = handleUpdateProduct;


    var parameterlist="prod_id="+prod_id+"&prod_name="+prod_name+"&prod_cart="+prod_cart+"&prod_m="+prod_m+"&prod_d="+prod_d+"&prod_p="+prod_p+"&prod_u="+prod_u;
    
    xhr4.open("GET", "InventoryServlet?"+parameterlist+"&searchOption=5", true);
    xhr4.setRequestHeader("Content-Type", "application/x-www-form-urlendoded");
    xhr4.send(null);

}
/*---------------------------------------------------------------------------*/
function handleUpdateProduct()
{if (xhr4.readyState != 4) return;
    if (xhr4.status != 200) {
        alert(xhr4.status); // for troubleshooting
        return;
    }
    var xhresponse = xhr4.responseXML;
       

	strResult = xhresponse.getElementsByTagName("myUpdateError");
        //alert(strResult);
        alert(strResult[0].firstChild.nodeValue);
           

      disable('strProductName');
      disable("strProductC");
      disable("strProductM");
      disable("strProductD");
      disable("strProductP");
      disable("strProductU");


}
function addProduct()
{if (window.ActiveXObject)
        xhr5 = new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
        xhr5 = new XMLHttpRequest;
    var prod_id=document.getElementById("strProductId").value;
    var prod_name=document.getElementById("strProductName").value;
    var prod_cart=document.getElementById("strProductC").value;
    var prod_m=document.getElementById("strProductM").value;
    var prod_d=document.getElementById("strProductD").value;
    var prod_p=document.getElementById("strProductP").value;
    var prod_u=document.getElementById("strProductU").value;
    xhr5.onreadystatechange = handleAddResults;
    var parameterlist="prod_id="+prod_id+"&prod_name="+prod_name+"&prod_cart="+prod_cart+"&prod_m="+prod_m+"&prod_d="+prod_d+"&prod_p="+prod_p+"&prod_u="+prod_u;

    xhr5.open("GET", "InventoryServlet?"+parameterlist+"&searchOption=6", true);
    xhr5.setRequestHeader("Content-Type", "application/x-www-form-urlendoded");
    xhr5.send(null);
}
/*---------------------------------------------------------------------------*/
function handleAddResults()
{if (xhr5.readyState != 4) return;
    if (xhr5.status != 200) {
        alert(xhr5.status); // for troubleshooting
        return;
    }
    var xhresponse = xhr5.responseXML;
      strResult = xhresponse.getElementsByTagName("myError");

        alert(strResult[0].firstChild.nodeValue);
        
    


}


/*****************************************************************************/